<template>
  <!-- 版本管理 -->
  <div class="promptl">
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :rowstyles="rowstyles"
      :onSyncTableData="DataHandle"
      height="auto"
      :isSelectColumn="false"
      :datakey="'records'"
      :onColumnsChange="columns => this.columns = columns"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addhandle">新增</el-button>
      </template>
    </FilterTable>
    <!-- 弹出框 -->
    <BaseDialog
      :visible.sync="showAddNew"
      :title="title"
      destroyOnClose
      width="40%"
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto',}"
    >
      <FormPanel
        ref="formPanel"
        :list="formList"
        :formType="type"
        labelWidth="80"
        :isSubmitBtn="false"
        :cols="1"
      />
      <!-- <div style="text-align: center;margin: 20px 0;">
        <uploadBreakpoint  :init="initSet"   @getUrl="getUrl" @errorHandler="errorHandler"/>
        <a
          style="display: block;height: 30px;line-height: 50px;"
          v-for="(item,k) of this.form.fileList"
          :href="item.url"
          :key="k"
          :download="item.name"
        >{{item.name}}</a>
      </div>-->
      <FormPanel
        ref="formPanel2"
        :list="formList2"
        :formType="type"
        labelWidth="100"
        :isSubmitBtn="false"
        :cols="1"
      />
      <div style="text-align: center;">
        <el-button size="small" type @click="closeHandler">取消</el-button>
        <el-button size="small" type="primary" :disabled="isDisabled" :loading="saveLoading"  @click="savehandle">保存</el-button>
      </div>
    </BaseDialog>
    <!-- 二维码下载 -->
    <el-dialog title="请扫描二维码下载APP" :visible.sync="qrCodeShow" width="300px" center>
      <qrCodeApp :qrcodeUrl="qrcodeUrl"  ref="funCodeUrl"/>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { queryAppVersion, queryAppVersionById, save } from '@/api/common/version/versionManage';
import { dictionary } from '@/utils/dictMixin';
import qrCodeApp from '@/pages/login/qrCodeApp/index';
import Cookies from 'js-cookie';
export default {
  name: 'promptl',
  mixins: [dictionary],
  data() {
    this.BaseTable = null;
    return {
      columns: this.createTableColumns(),
      formList: this.createFormList(),
      formList2: this.createFormList2(),
      fetchApi: queryAppVersion,
      fetchParams: {},
      showAddNew: false,
      qrCodeShow: false,
      qrcodeUrl: '',
      type: 'add',
      title: '',
      allData: '',
      rowstyles: [],
      upLoadArr: '',
      isDisabled: true,
      saveLoading : false
      /* initSet: {
        //上传文件初始配置
        url: '/api/file/oss/upload', //上传地址
        chunkSize: 1, //分片大小
        userId: '', //标识，文件唯一标志，可以判断由那个用户上传
        bucketType: 'public', //桶的类型（public：公有，private: 私有）
        accept: ['apk', 'ipa'], //支持格式
        initialValue: [] //图片名称、地址
      }, */
      /* form: {
        fileList: [],
        upLoadFileName: '',
        upLoadUrl: ''
      } */
    };
  },
  components: {
    qrCodeApp
    // wxlogin
  },
  methods: {
    init() {},
    DataHandle(data, isOverdue) {
      // console.log('data',data)
      if (!data.length) return;
      // 当天日期
      data.forEach(x => {
        if (x.status == 10011001) {
          // console.log(x,"x")
          this.rowstyles.push({ row: x, styles: { background: '#FFCCCC' } });
        }
      });
    },
    /* getCheckedList(orgId,isAdd){
        // getRole
          this.sites=[]
          getRole(this.RoleEmployeeNo,orgId,isAdd)
            .then(res => {
              this.sites = _.cloneDeep(res.data)
            })
            .catch(err => {
            })
      }, */
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.editHandle(props.row)}>
                  编辑
                </el-button>
              </div>
            );
          }
        },
        /* {
            title: '序号',
            dataIndex: 'index',
            width: 70,
            sorter: true,
            render: props => {
              return <span>{props.row.index + 1}</span>;
            }
          }, */
        {
          title: '平台',
          dataIndex: 'appType',
          sorter: true,
          filter: true,
          filterType: 'input'
          // align:"center"
        },
        {
          title: '版本号',
          dataIndex: 'versionNo',
          sorter: true,
          filter: true,
          filterType: 'input'
          // align:"center"
        },
        {
          title: '版本状态',
          dataIndex: 'status',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1001'),
          render: props => {
            return <span>{this.createDictText(props.row.status, '1001')}</span>;
          }
          // align:"center"
        },
        {
          title: '强制更新',
          dataIndex: 'isForced',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.isForced, '1004')}</span>;
          }
        },
        {
          title: '更新描述',
          dataIndex: 'remark',
          sorter: true,
          filter: true,
          filterType: 'input'
          // align:"center"
        },
        {
          title: 'APP下载',
          dataIndex: 'url',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return (<p style="cursor: pointer;" onClick={() => this.downApp(props.row)}>
                    查看二维码
                </p>
            );
          }
          // align:"center"
        },
        {
          title: '创建者',
          dataIndex: 'createdMan',
          sorter: true,
          filter: true,
          filterType: 'input'
          // align:"center"
        },
        {
          title: '更新时间',
          dataIndex: 'createdDate',
          sorter: true,
          filter: true,
          filterType: 'input'
          // align:"center"
        }
      ];
    },

    createFormList() {
      return [
        {
          type: 'SELECT',
          label: '平台',
          disabled: true,
          fieldName: 'appType',
          itemList: [{ text: 'IOS', value: 'IOS' }, { text: 'Android', value: 'Android' }],
          rules: [{ required: true, message: '请选择平台', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '版本号',
          disabled: true,
          fieldName: 'versionNo',
          maxlength: 16,
          rules: [{ required: true, message: '请输入版本号', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '强制更新',
          fieldName: 'isForced',
          disabled: true,
          itemList: this.createDictList('1004'),
          initialValue: 10041001
        },
        {
          type: 'UPLOAD_ALIOSS',
          label: '上传文件',
          fieldName: 'upLoadUrl',
          disabled: !0,
          upload: {
            fileTypes: ['apk', 'ipa'],
            limit: 1
          },
          change: val => {
            console.log(val, '文件');
            if (val) {
              this.formList.find(x => x.fieldName == 'upLoadUrl').initialValue = val;
              this.upLoadArr = val;
              this.isDisabled = false;
            }
          },
          initialValue: []
        }
        /* {
          type: 'UPLOAD_FILE',
          label: '上传',
          fieldName: 'url',
          placeholder: '上传文件...',
          rules: [{ required: true, message: '请上传文件', trigger: 'change' }],
          initialValue: [{ name: '', url: '' }],
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 1,
            fileSize:100,
            fileTypes: ['apk','ipa','jpg']
          }
        }, */
      ];
    },
    createFormList2() {
      return [
        {
          type: 'TEXT_AREA',
          label: '更新描述',
          fieldName: 'remark',
          maxlength: 200,
          rules: [{ required: true, message: '更新描述', trigger: 'blur' }]
        }
      ];
    },
    //新增
    addhandle() {
      this.isDisabled = true;
      this.title = '新增';
      this.showAddNew = true;
      this.type = 'add';
      this.formList.forEach(x => {
        if (x.disabled) {
          x.disabled = false;
        }
        x.initialValue = '';
      });
      this.formList2.find(x => x.fieldName == 'remark').initialValue = '';
      // this.form.fileList = [];
      this.formList.find(x => x.fieldName == 'upLoadUrl').initialValue = [];
      this.formList.find(x => x.fieldName == 'isForced').disabled = true;
      this.formList.find(x => x.fieldName == 'isForced').initialValue = 10041001;
    },
    // 编辑
    async editHandle(row, dataTypes) {
      console.log('编辑row',row)
      console.log('编辑dataTypes',dataTypes)

      this.allData = row;
      this.isDisabled = false;
      this.type = 'edit';
      this.title = '编辑';
      this.showAddNew = true;
      let that = this;
      await queryAppVersionById(row.versionId).then(res => {
        if (res.resultCode == 200) {
          this.formList.forEach(x => {
            x.initialValue = res.data[x.fieldName];
          });
          console.log(res, '编辑');
          this.formList2.find(x => x.fieldName == 'remark').initialValue = res.data['remark'];
          this.formList.find(x => x.fieldName == 'upLoadUrl').initialValue = [{ name: res.data.fileName, url: res.data.url }];
          this.upLoadArr = [{ name: res.data.fileName, url: res.data.url }];
          this.formList.find(x => x.fieldName == 'isForced').initialValue = 10041001;
          this.formList.find(x => x.fieldName == 'appType').disabled = true;
          this.formList.find(x => x.fieldName == 'versionNo').disabled = true;
        }
      });

    },
    //下载
    downApp(row) {
      Cookies.set('appUrl', row.url);
      Cookies.set('appType', row.appType);
      var url = window.location.href;
      var domain = url.split('/');
      this.qrcodeUrl = `${domain[0]}//${domain[2]}/wxVersion?url=${row.url}&appType=${row.appType}`;
      this.qrCodeShow = true;
      this.$nextTick(() => {
           this.$refs.funCodeUrl.handleQrcodeToDataUrl(this.qrcodeUrl)
       })

    },
    getUrl(file, val) {
      console.log('返回上传成功文件', file, val);
      if (file) {
        console.log(file, '导入');
        this.upLoadFileName = file.name;
        this.upLoadUrl = val.data;
        this.isDisabled = false;
        // this.form.fileList = val;
      }
    },
    errorHandler() {
      this.isDisabled = true;
    },
    successHandler(val) {
      console.log('返回上传成功文件', val);
    },
    /* successHandler(val) {
      if(val&&val.length>0){
          console.log(val,"导入")
          this.upLoadFileName=val[0].name
          this.upLoadUrl=val[0].url
          this.isDisabled=false
          this.form.fileList = val;
        }
      },
      errorHandler(val){
        console.log(val,"删除")
      }, */
    //保存
    savehandle() {
      let data = this.$refs['formPanel'].SUBMIT_FORM();
      let params = {
        ...data,
        fileName: this.upLoadArr[0].name,
        url: this.upLoadArr[0].url.split('?')[0],
        remark: this.formList2.find(x => x.fieldName == 'remark').initialValue,
        status: 10011001,
        versionNo: this.formList.find(x => x.fieldName == 'versionNo').initialValue,
        versionId: this.allData.versionId ? this.allData.versionId : ''
      };
      if(params.url.match('^http://')){
        params.url=params.url.replace(/^http:\/\//i,'https://');
      }
      if (data) {
        this.saveLoading = true;
        save(params).then(res => {
          if (res.resultCode == 200) {
            this.$message({
              message: `保存成功`,
              type: 'success'
            });
            this.closeHandler('refresh');
          } else {
          }
             this.saveLoading = false;
        });
      }
    },
    //关闭
    closeHandler(type) {
      this.showAddNew = false;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    }
  },

  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.init();
  }
};
</script>

<style lang="less" scoped>
</style>
